package com.hgyc.mom.mes.websocket.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SemaphoreUtils.class);

    /**
     * 默认尝试立即获取信号量
     *
     * @param semaphore 信号量对象
     * @return 是否获取成功
     */
    public static boolean tryAcquire(Semaphore semaphore) {
        if (semaphore == null) return false;
        try {
            return semaphore.tryAcquire();
        } catch (Exception e) {
            LOGGER.error("获取信号量异常", e);
            return false;
        }
    }

    /**
     * 限时获取信号量
     *
     * @param semaphore 信号量对象
     * @param timeoutMs 等待时间（毫秒）
     * @return 是否获取成功
     */
    public static boolean tryAcquire(Semaphore semaphore, long timeoutMs) {
        if (semaphore == null) return false;
        try {
            return semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            LOGGER.error("限时获取信号量异常", e);
            return false;
        }
    }

    /**
     * 释放信号量
     *
     * @param semaphore 信号量对象
     */
    public static void release(Semaphore semaphore) {
        if (semaphore == null) return;
        try {
            semaphore.release();
        } catch (Exception e) {
            LOGGER.error("释放信号量异常", e);
        }
    }
}
